<?php
namespace App\Socket\Logic;
use EasySwoole\Core\Socket\Client\WebSocket;
use App\Socket\Model\User;
use App\Socket\Model\Room;

class UserLogic extends Base{

    /**
     * 用户登录
     * 将fd与uid进行关联
     * @param integer $fd
     * @param array $user
     * @return void
     */
    public static function login(WebSocket $client, $param){            
        $fd = $client->getFd();
        $username = $param["username"];
        $password = $param["password"];        

        $user = User::where("username",$username)->find();                          
       
        if (empty($user)) {
            $res=[
                "cmd"=>"error",
                "data"=>[
                    "msg"=>"用户不存在,请先注册"
                ]
            ];
        } else {
            //判断密码是否正确
            if ($password!=$user->getData("password")) {
                $res=[
                    "cmd"=>"error",
                    "data"=>[
                        "msg"=>"密码不正确"
                    ]
                ];
            } else {                                
                $old = $user->fd;
                if($old){
                    //禁止多点登录
                    $msg =[
                        "cmd"=>"error",
                        "data"=>[
                            "msg"=>"帐号在其他地方登录"
                        ]
                    ];
                    self::push($old,$msg);
                    self::closeFd($old);
                }
                
                
                $user->fd = $fd;                    
                $user->save();                                                                       
                $res=[
                    "cmd"=>"login",
                    "data"=>[
                        "user"=>$user
                    ]
                ];                
            }
        }                 
        self::push($fd,$res);
    }
    
    /**
     * 用户注册     
     * @param WebSocket $client
     * @return void
     */
    public static function reg(WebSocket $client,$username,$password){
        $fd = $client->getFd();

        $user = new User([
            "username" => $username,
            "password" => $password
        ]);
        
        $res = [];

        try{
            $user->save();
            $res["cmd"] = "regSuccess";
            
        }catch(\Exception $e){
            $res["cmd"] = "error";
            $res["data"] = [
                "msg"=>"帐号已存在"
            ];  
        }
        self::push($fd,$res);
    }


    /**
     * 进入房间     
     * 1 房间是否存在 
     * 1.1 不存在则创建房间
     * 1.2 存在， 判断当前房间人数
     * 1.2.1 如果房间小于N人，加入
     * 1.2.2 如果房间大于N人, error
     * @param integer $fd
     * @param integer $rid
     * @return void
     */
    public static function joinRoom(WebSocket $client,int $rid){
        $fd = $client->getFd();
        $user = $client->getData();

        $room = Room::where("rid",$rid)->find();
        if($room && $room->Users){
            $users = $room->Users;
            $point = $room->point;
           
            foreach($users as $item){
                if(!self::checkFd($item->fd)){
                    $item->fd = null;
                    $item->save();
    
                    $index = array_search($item->uid,$point);
                    if($index!==false){
                        array_splice($point,$index,1);                    
                    }            
                }
            }
        
            $room->point = $point;
        }


      
        if($room &&  count($room->point)==3 ){
            //房间已满
            $res = [
                "cmd"=>"error",
                "data"=>[
                    "msg"=>"房间已满"
                ]
            ];
            self::push($fd,$res);            
            return ;
        }
        
        $user->rid = $rid;
        $user->save();
        if( empty($room) ){
            $room = new Room();
            $room->rid = $rid;
            $room->point=[$user->uid];                      
        }else{            
            $point = $room->point;
            //先判断当前用户是否已在房间内

            if(in_array($user->uid,$point)){
               return ; 
            }
            array_push($point,$user->uid);
            $room->point = $point;            
        }
        $room->save();    


        $res=[
            "cmd"=>"intoRoom",
            "data"=>[
                "user"=>$user,
                "rid"=>$rid
            ]
        ];         
        //通知房间内的人，有人进入房间        
        self::notice($res,$room);
       
        //发送房间用户列表给当前客户端        
        $res=[
            "cmd"=>"roomUserInfo",
            "data"=>[
                "users"=>$room->Users,
                "rid"=>$rid
            ]
        ];
        self::push($fd,$res);


        //如果房间人数已满,通知客户端显示准备按钮
        if(count($room->Users)==3){
            $res=[
                "cmd"=>"showReadyButton",
                "data"=>""
            ];
            self::notice($res,$room);    
        }

    }

    /**
     * 获取房间用户信息
     *
     * @param [type] $rid
     * @return void
     */
    public static function getRoomUsers($rid){        
        $list = Room::where("rid",$rid)->select();        
        $users = [];
        foreach($list as $item){            
            $users[] = $item->User;
        }        
        return $users;
    }

    /**
     * 退出房间     
     * @param [type] $fd
     * @param [type] $rid
     * @return void
     */
    public static function exitRoom(User $user=null){        
        if($user && $user->Room){                        
            $room = $user->Room;
            $point = $room->point;            
            $index = array_search($user->uid,$point);
            if($index>=0){
                array_splice($point,$index,1);
            }
            $room->point = $point;
            
            $room->outCard = null;
            $room->baseCard = null;
            $room->handCard = null;
            $room->ready = null;
            $room->score=null;
            $room->landlord = null;
            $room->nextOutUid = null;
            $room->save();
        
            //退出房间时通报
            if( count($point) ){
                $room->save();
            }else{
                $room->delete();
            }            
            $msg=[
                "cmd"=>"exitRoom",
                "data"=>[
                    "user"=>$user
                ]
            ];    
            self::notice($msg,$room);    
        }                        
    }

    /**
     * 连接关闭     
     * @param integer $fd
     * @return void
     */
    public static function close(int $fd){
        $user = User::where("fd",$fd)->find();
        if($user){
            self::exitRoom($user);        
            $user->fd = null;
            $user->rid = null;
            $user->save();    
        }        
    }
}